import React, { useEffect, useState } from "react";
import { Card, Row, Col, Slider, Switch, Statistic, Space, Divider } from "antd";
import {
    ThermometerOutlined,
    DropboxOutlined,
    WindOutlined,
    SunOutlined,
    WaterOutlined,
    ThunderboltOutlined,
    CloudFilled,
    FanOutlined,
    BulbOutlined
} from "@ant-design/icons";
import axios from "axios";

const api = "http://localhost:5000/api";

function App() {
    const [data, setData] = useState({});
    const [loading, setLoading] = useState(false);

    const fetchData = async () => {
        try {
            const res = await axios.get(`${api}/data`);
            setData(res.data);
        } catch (error) {
            console.error("获取数据失败:", error);
        }
    };

    useEffect(() => {
        fetchData();
        const timer = setInterval(fetchData, 2000);
        return () => clearInterval(timer);
    }, []);

    const handleControl = async (key, value) => {
        setLoading(true);
        try {
            await axios.post(`${api}/control`, { [key]: value });
            fetchData();
        } catch (error) {
            console.error("控制失败:", error);
        }
        setLoading(false);
    };

    // 计算AQI等级和颜色
    const getAQILevel = (aqi) => {
        if (aqi <= 50) return { level: "优", color: "#52c41a" };
        if (aqi <= 100) return { level: "良", color: "#faad14" };
        if (aqi <= 150) return { level: "轻度污染", color: "#fa8c16" };
        if (aqi <= 200) return { level: "中度污染", color: "#f5222d" };
        return { level: "重度污染", color: "#722ed1" };
    };
    const aqiInfo = getAQILevel(data.AQI || 0);

    // 图表占位（可替换为实际图表组件）
    const ChartPlaceholder = () => (
        <Card style={{ marginBottom: 12, minHeight: 180, textAlign: 'center', background: '#f6f8fa' }}>
            <div style={{ color: '#bfbfbf', fontSize: 18, lineHeight: '180px' }}>
                图表区域（可集成ECharts等）
            </div>
        </Card>
    );

    return (
        <div style={{
            padding: 16,
            background: "linear-gradient(135deg, #e0e7ff 0%, #f8fafc 100%)",
            minHeight: "100vh",
            fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif"
        }}>
            <div style={{
                background: "#fff",
                borderRadius: 12,
                padding: 20,
                boxShadow: "0 8px 32px rgba(0,0,0,0.08)",
                maxWidth: 1400,
                margin: "0 auto"
            }}>
                <h1 style={{
                    textAlign: "center",
                    marginBottom: 16,
                    color: "#2c3e50",
                    fontSize: 26,
                    fontWeight: 600
                }}>
                    🌱 智慧农业监控系统
                </h1>
                <Row gutter={16}>
                    {/* 左侧：图表+传感器数据 */}
                    <Col span={16}>
                        <ChartPlaceholder />
                        <Card
                            title={<span><CloudFilled style={{ marginRight: 8 }} />传感器数据</span>}
                            bordered={false}
                            bodyStyle={{ padding: 12 }}
                            style={{ marginBottom: 0 }}
                        >
                            <Row gutter={[8, 8]}>
                                <Col span={6}>
                                    <Statistic
                                        title="温度"
                                        value={data.temperature || 0}
                                        suffix="°C"
                                        prefix={<ThermometerOutlined style={{ color: "#ff4d4f" }} />}
                                        valueStyle={{ color: "#ff4d4f", fontSize: 18 }}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic
                                        title="湿度"
                                        value={data.Humidity || 0}
                                        suffix="%"
                                        prefix={<DropboxOutlined style={{ color: "#1890ff" }} />}
                                        valueStyle={{ color: "#1890ff", fontSize: 18 }}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic
                                        title="风速"
                                        value={data.WindSpeed || 0}
                                        suffix="m/s"
                                        prefix={<WindOutlined style={{ color: "#52c41a" }} />}
                                        valueStyle={{ color: "#52c41a", fontSize: 18 }}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic
                                        title="光照"
                                        value={data.LightLux || 0}
                                        suffix="lux"
                                        prefix={<SunOutlined style={{ color: "#faad14" }} />}
                                        valueStyle={{ color: "#faad14", fontSize: 18 }}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic
                                        title="土壤湿度"
                                        value={data.soilHumidity || 0}
                                        suffix="%"
                                        prefix={<WaterOutlined style={{ color: "#722ed1" }} />}
                                        valueStyle={{ color: "#722ed1", fontSize: 18 }}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic
                                        title="紫外线"
                                        value={data.UV || 0}
                                        prefix={<ThunderboltOutlined style={{ color: "#fa8c16" }} />}
                                        valueStyle={{ color: "#fa8c16", fontSize: 18 }}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic
                                        title="空气质量"
                                        value={data.AQI || 0}
                                        prefix={<CloudFilled style={{ color: aqiInfo.color }} />}
                                        valueStyle={{ color: aqiInfo.color, fontSize: 18 }}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic
                                        title="最后更新时间"
                                        value={new Date().toLocaleString()}
                                        prefix={<ThunderboltOutlined style={{ color: "#bfbfbf" }} />}
                                        valueStyle={{ color: "#bfbfbf", fontSize: 14 }}
                                    />
                                </Col>
                            </Row>
                        </Card>
                    </Col>
                    {/* 右侧：设备控制区 */}
                    <Col span={8}>
                        <Space direction="vertical" style={{ width: "100%" }} size="middle">
                            <Card
                                title={<span><FanOutlined style={{ marginRight: 8 }} />风扇控制</span>}
                                bordered={false}
                                bodyStyle={{ padding: 12 }}
                            >
                                <Statistic
                                    value={data.FanLevel || 0}
                                    suffix="/5"
                                    valueStyle={{ fontSize: 24, color: "#1890ff" }}
                                    style={{ marginBottom: 8 }}
                                />
                                <Slider
                                    min={0}
                                    max={5}
                                    value={data.FanLevel || 0}
                                    onChange={val => handleControl("FanLevel", val)}
                                    disabled={loading}
                                    marks={{ 0: "关", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5" }}
                                />
                            </Card>
                            <Card
                                title={<span><BulbOutlined style={{ marginRight: 8 }} />LED灯控制</span>}
                                bordered={false}
                                bodyStyle={{ padding: 12 }}
                            >
                                <Statistic
                                    value={data.LEDLux || 0}
                                    suffix="/5"
                                    valueStyle={{ fontSize: 24, color: "#faad14" }}
                                    style={{ marginBottom: 8 }}
                                />
                                <Slider
                                    min={0}
                                    max={5}
                                    value={data.LEDLux || 0}
                                    onChange={val => handleControl("LEDLux", val)}
                                    disabled={loading}
                                    marks={{ 0: "关", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5" }}
                                />
                            </Card>
                            <Card
                                title={<span><WaterOutlined style={{ marginRight: 8 }} />水泵控制</span>}
                                bordered={false}
                                bodyStyle={{ padding: 12 }}
                            >
                                <Switch
                                    checked={!!data.IrrigationPumpStatus}
                                    checkedChildren="开启"
                                    unCheckedChildren="关闭"
                                    onChange={val => handleControl("IrrigationPumpStatus", val ? 1 : 0)}
                                    disabled={loading}
                                    size="large"
                                    style={{ marginBottom: 8 }}
                                />
                                <div style={{
                                    fontSize: 16,
                                    fontWeight: "bold",
                                    color: data.IrrigationPumpStatus ? "#52c41a" : "#ff4d4f"
                                }}>
                                    {data.IrrigationPumpStatus ? "水泵运行中" : "水泵已停止"}
                                </div>
                            </Card>
                        </Space>
                    </Col>
                </Row>
            </div>
        </div>
    );
}

export default App; 